import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams, Platform, ModalController, ViewController } from 'ionic-angular';

import { AppConfig } from '../../app/app.config';
import { UtilsService } from '../../providers/utils.service';
import { HttpsService } from "../../providers/http.service";
import { MinePage } from '../mine/mine';
// 引入微信服务
declare var Wechat:any;
/**
 * Generated class for the LoginPage page.
 *
 * See https://ionicframework.com/docs/components/#navigation for more info on
 * Ionic pages and navigation.
 */

@IonicPage()
@Component({
  selector: 'page-login',
  templateUrl: 'login.html',
})
export class LoginPage {
  private platform:Platform;
  constructor(public navCtrl: NavController, public navParams: NavParams, private http:HttpsService, private modalCtrl:ModalController, private utils:UtilsService, private viewCtrl:ViewController) {
  }

  ionViewDidLoad() {
    console.log('ionViewDidLoad LoginPage');
  }

  wechatLogin1() {
    // window.open('https://itunes.apple.com/cn/app/%E5%BE%AE%E4%BF%A1/id414478124?mt=8');
    let contactModal = this.modalCtrl.create(MinePage);
    contactModal.present();
  }
  wechatLogin2() {
    window.open('https://weixin.qq.com/cgi-bin/readtemplate?uin=&stype=&promote=&fr=&lang=zh_CN&ADTAG=&check=false&t=weixin_download_method&sys=android&loc=weixin,android,web,0');
  }


  wechatLogin() {
    Wechat.isInstalled(isInstalled => {
      if (!isInstalled) {
        if (this.platform.is('ios')) {
          // this.bs.launchOutter('https://itunes.apple.com/cn/app/%E5%BE%AE%E4%BF%A1/id414478124?mt=8');
        }
        else if (this.platform.is('android')) {
          // this.bs.launchOutter('https://weixin.qq.com/cgi-bin/readtemplate?uin=&stype=&promote=&fr=&lang=zh_CN&ADTAG=&check=false&t=weixin_download_method&sys=android&loc=weixin,android,web,0');
        }
        else {
          this.utils.showLoading('请先安装微信客户端');
        }
        // alert("Wechat installed: " + (isInstalled ? "Yes" : "No"));
      } else {
        console.log("wechat login.....")
        let loader = this.utils.showLoading('跳转微信登录中...')
        try {
          var scope = "snsapi_userinfo";//snsapi_userinfo
          var state = "_" + (+new Date());
          //获取code
          console.log("error===");
          //文档地址: https://open.weixin.qq.com/cgi-bin/showdocument?action=dir_list&t=resource/res_list&verify=1&id=open1419317851&token=&lang=zh_CN
          //跳转到微信
          Wechat.auth(scope, state, (res) => {
            //用户点击授权后，微信客户端会被拉起，跳转至授权界面，用户在该界面点击允许或取消
            console.log(JSON.stringify(res))
            //在调用service的getAccessToken方法获取access_token，和acopenid，
            let url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + AppConfig.APPID + "&secret=" + AppConfig.APPSECRET + "&code=" + res.code + "&grant_type=authorization_code";
            // let loader = this.utils.showLoading("");
            this.http.get(url, null, (res)=>{
              console.log("openid===="+res.openid+", access_token=="+res.access_token);
              this.getUserInfo(res);
            }, (err)=>{
              console.log("err==="+JSON.stringify(err));
            })
            //然后再service的getWechatUserInfo方法获取微信用户的基本信息，最后保存登录，完成
          }, (reason) => {
            console.log(reason);
          });
        } catch (error) {
          console.log("error===" + error);
        } finally {
          this.utils.hideLoading(loader);
        }
      } 
    })
  }

  getUserInfo(res) {
    //方法一
    let url = "https://api.weixin.qq.com/sns/userinfo?access_token=" + res.access_token + "&openid=" + res.openid + "&lang=zh_CN"   
    this.http.get(url, null, (res) => {
      alert(JSON.stringify(res));
    }, (err)=>{

    });
    //方法2 
    if(!res.openid){
      this.utils.presentLoadingText('微信授权信息出错');
    } else {
      this.http.get("http://passport.cqzuxia.com/api/Authorize/GetAccountByWechatID", {openid: res.openid, type: '1'}, (res)=>{
        // this.utils.hideLoading();  
        
        // if (res.Success) {

        //   if (res.Data.Type == 0) {
        //     //未绑定
        //     let modal = this.modalCtrl.create(BindAccountPage, {
        //       openid: openid,
        //       type: this.loginInfo.type
        //     });
        //     modal.onDidDismiss(data => {
        //       if (data) {
        //         this.loginInfo.LoginID = data.username;
        //         this.loginInfo.LoginPwd = data.password;
        //         this.login(this.loginInfo);
        //       }
        //     });
        //     modal.present();
        //   }
        //   else if (res.Data.Type == 1) {
        //     //已绑定
        //     this.loginInfo.LoginID = res.Data.Username;
        //     this.loginInfo.LoginPwd = res.Data.Password;
        //     this.login(this.loginInfo, true);
        //   }
        // }
        
      }, (err) => {
        this.utils.presentLoadingText(JSON.stringify(err));
      })
    }
  }

  dismiss() {
    this.navCtrl.pop();
    // this.viewCtrl.dismiss();
  }
}
